#include <iostream>
#include <istream>
#include <ostream>
#include <string>
#include <boost/asio.hpp>
#include <fstream>

#include "http_request.h"

#define PROXY 1

using boost::asio::ip::tcp;

HTTPRequest::HTTPRequest(std::string proxy) : _proxy(proxy + "\r\n")
{

}

void	HTTPRequest::setProxy(std::string proxy)
{
	this->_proxy = proxy + "\r\n";
}

int		HTTPRequest::getRSS(std::string path)
{
  try
  {
	std::string port;
	std::string server;
    boost::asio::io_service io_service;
	std::ofstream xmlfile;
	xmlfile.open ("tmp.xml");

    tcp::resolver resolver(io_service);
	
	if (this->_proxy != "")
	{
			server = "proxies.epitech.net";
			port = "3128";
	}
	else
	{
		if (path.substr(0, 7) == "http://")
			path = path.substr(7);
		server = path.substr(0, path.find_first_of('/'));
		port = "80";
	}
    tcp::resolver::query query(server, port);
	
    tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
    tcp::resolver::iterator end;

    tcp::socket socket(io_service);
    boost::system::error_code error = boost::asio::error::host_not_found;
    while (error && endpoint_iterator != end)
    {
      socket.close();
      socket.connect(*endpoint_iterator++, error);
    }
    if (error)
      throw boost::system::system_error(error);

    boost::asio::streambuf request;
    std::ostream request_stream(&request);
	if (this->_proxy != "")
		request_stream << "GET " << path << " HTTP/1.1\r\n";	
	else
		request_stream << "GET / HTTP/1.1\r\n";
	if (this->_proxy != "")
		{
			request_stream << "Proxy-Authorization: Basic " << this->_proxy;
			if (path.substr(0, 7) == "http://")
				path = path.substr(7);
			path = path.substr(0, path.find_first_of('/'));
		}
	request_stream << "Host: " << path << "\r\n" << "Accept: */*\r\n" << "Connection: close\r\n\r\n";

    boost::asio::write(socket, request);

    boost::asio::streambuf response;
    boost::asio::read_until(socket, response, "\r\n");

    std::istream response_stream(&response);
    std::string http_version;
    response_stream >> http_version;
    unsigned int status_code;
    response_stream >> status_code;
    std::string status_message;
    std::getline(response_stream, status_message);
    if (!response_stream || http_version.substr(0, 5) != "HTTP/" || status_code != 200)
		throw boost::system::system_error(error);

    boost::asio::read_until(socket, response, "\r\n\r\n");
    std::string header;
	while (std::getline(response_stream, header) && header != "\r");

    if (response.size() > 0)
      xmlfile << &response;

    while (boost::asio::read(socket, response, boost::asio::transfer_at_least(1), error))
      xmlfile << &response;
    if (error != boost::asio::error::eof)
      throw boost::system::system_error(error);
	xmlfile.close();
	return 0;
  }
  catch (std::exception& e)
  {
    std::cout << "Exception: " << e.what() << "\n";
  }
  return (-1);
}
